package com.yfk.web.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yfk.base.event.pojo.QWConfigVO;
import com.yfk.web.entity.YHTVO;
import com.yfk.web.util.BIPUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("YHTService")
public class YHTAndQWController {

    Logger logger = LoggerFactory.getLogger(YHTAndQWController.class);
    @Autowired
    public QWConfigVO qwVO;

    /**
     *
     * @return
     * @throws Exception
     */
    @RequestMapping("/auth")
    public void QWApproveDetail(@RequestParam("userid") String userid, @RequestParam("redirectUrl") String redirectUrl, HttpServletRequest req, HttpServletResponse resp ) throws  Exception{
        logger.info("准备获取友合同token##");
        String webURl = redirectUrl.replaceAll(";","&");
        String baseURL = this.qwVO.getYhtBaseURL();
        String qwProxy = this.qwVO.getQwProxy();
        // 替换系统地址为待办地址
//        webURl = webURl.replace(baseURL, qwProxy);
//        baseURL = baseURL.replaceAll(baseURL, qwProxy);
        String redirectUrl1 = URLEncoder.encode(baseURL+"/login?service="+URLEncoder.encode(webURl, StandardCharsets.UTF_8.toString()),
                StandardCharsets.UTF_8.toString());
        logger.info("重定向地址 redirectUrl1 = " + redirectUrl1);
        String tokenURL = this.getTokenURL(baseURL);
        logger.info("获取token 地址  tokenURL = " + baseURL);
        String access_Token = BIPUtil.getAccessToken(tokenURL, this.qwVO.getAppKey(), this.qwVO.getAppSecret());
        String loginURL = String.format("%s/cas/thirdOauth2CodeLogin?thirdUCId=%s&code=%s&service=%s", baseURL,
                this.qwVO.getJcrzzx(), this.getThirdLoginCode(baseURL,this.qwVO.getGetThirdLoginCode(),this.qwVO.getJcrzzx(),userid,access_Token), redirectUrl1);
        logger.info("单点登录地址loginURL = " + loginURL);
        resp.sendRedirect(loginURL);;
    }

    /**
     * 获取tokenURL
     * @return
     * @throws Exception
     */
    public String getTokenURL(String baseURL) throws Exception{
        return baseURL + "/iuap-api-auth/open-auth/selfAppAuth/getAccessToken";
    }

    /**
     * 获取临时code
     * @param thirdUcId
     * @param userId
     * @param accessToken
     * @return
     * @throws Exception
     */
    public String getThirdLoginCode(String baseURL, String getThirdLoginCodeURL,String thirdUcId, String userId, String accessToken) throws Exception{
        String code = "111";
        Map queryParams = new HashMap<>();
        queryParams.put("access_token", accessToken);
        String s = baseURL + "/iuap-api-gateway" + getThirdLoginCodeURL;
        JSONObject bodyJSON = new JSONObject();
        bodyJSON.put("thirdUcId", thirdUcId);
        bodyJSON.put("userId", userId);
        String res = BIPUtil.getPostQueryParamAndBodyParam(s, queryParams, bodyJSON);
        JSONObject json = JSON.parseObject(res);
        if("200".equals(json.getString("code"))){
            code = json.getJSONObject("data").getString("code");
        }
        return code;
    }

}
